import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store/modules/user'
import LAYOUT from '@/Layout/topLayout'
import { LOGIN_URL, ROUTER_WHITE_LIST } from "@/config/config";

import sceneRoutes from '@/router/scene';
import BIRoutes from '@/router/BI';
import algorithmRoutes from '@/router/algorithm';
import stagePowerRoutes from '@/router/stagePower';
// 省略了routes 中的路由规则
const routes = [{
    path: "/login", name: 'login',
    meta: {
        isHide: true,
    },
    component: () => import('@/views/Login.vue'),
}, {
    path: '/', component: LAYOUT, redirect: '/home', children: [{
        path: '/home', name: 'home', component: () => import('@/views/PgHome'), meta: {
            title: '首页', icon: 'UserFilled', keepAlive: true
        },
    }, //编辑工作台
    {
        path: '/PgScene', name: 'PgScene', meta: {
            // title: '工作台',
            // keepAlive: true
        }, props($route) {
            return {
                id: $route.query.id
            }
        }, component: () => import('@/views/scene/PgScene')
    }, {
        path: '/pgIframe/:url?', name: 'PgIframe', meta: {
            keepAlive: true
        }, component: () => import('@/views/PgIframe')
    }, {
        path: '/pgPowerEvolution', name: 'pgPowerEvolution', meta: {
            keepAlive: true, title: '电源演变'
        }, component: () => import('@/views/powerEvolution/PgPowerEvolution')
    }, ...sceneRoutes, ...BIRoutes, ...algorithmRoutes, ...stagePowerRoutes]
}]

const router = createRouter({
    history: createWebHashHistory(), base: '/gpapdm/', routes
})

const p = new Promise((resolve, reject) => {
    window.addEventListener('message', e => {
        if (typeof e.data === 'string') {
            resolve(e.data)
            store.commit("updateToken", e.data);
        } else {
            reject('token为空')
        }
    })
})
// 全局守卫：登录拦截 本地没有存token,请重新登录
router.beforeEach(async (to, from, next) => {
    // await p
    try {
        const tokenResult = await p
    } catch (e) {
        console.log(e)
    }
    //判断是否有标题
    if (to.meta.title) {
        document.title = to.meta.title
    }
    // 1.判断是访问登陆页，有 Token 就在当前页面，没有 Token 重置路由并放行到登陆页
    // if (to.path === LOGIN_URL) {
    //     if (store.state.token) return next(from.fullPath)
    //     next()
    //     return
    // }

    // 2.判断访问页面是否在路由白名单(不需要登陆)地址中，如果存在直接放行
    if (ROUTER_WHITE_LIST.includes(to.path)) return next()

    // 3.判断是否有 Token，没有token跳转到登陆页面并且携带原目标路径
    if (!store.state.token) {
        // return next({ path: LOGIN_URL })
        const loginUrl = localStorage.getItem('loginURL')
        if (loginUrl) {
            return top.location.href = loginUrl
        }
    }

    /* 
       // 4.如果没有菜单列表，就重新请求菜单列表并添加动态路由
          const authStore = useAuthStore()
          authStore.setRouteName(to.name as string)
          if (!authStore.authRouterList.length) {
              await initDynamicRouter()
              return next({ ...to, replace: true })
          }*/
    // 5.上述条件都不满足，直接放行.
    next()
})

router.afterEach((to, from) => {
    // /sceneView
    // console.log(to);
    if (to.path == '/sceneView') {//进行路由拦截
        store.commit('changeTabsName', 'PgScene')//选中进行高亮展示
        store.commit('changeTabs', {//创建工作台
            fullPath: "/PgScene", name: '/PgScene', meta: {
                title: '工作台', keepAlive: true,
            }
        })
    } else {
        store.commit('changeTabs', to)
    }


})


export default router
